<meta charset="utf-8">
(#) Implicit SAM Instances

!!! WARNING: Implicit SAM Instances
   This is a warning.

Id
:   `ImplicitSamInstance`
Summary
:   Implicit SAM Instances
Severity
:   Warning
Category
:   Correctness
Platform
:   Any
Vendor
:   Android Open Source Project
Feedback
:   https://issuetracker.google.com/issues/new?component=192708
Since
:   3.4.0 (April 2019)
Affects
:   Kotlin and Java files
Editing
:   This check runs on the fly in the IDE editor
See
:   https://kotlinlang.org/docs/fun-interfaces.html#sam-conversions
Implementation
:   [Source Code](https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-main:lint/libs/lint-checks/src/main/java/com/android/tools/lint/checks/SamDetector.kt)
Tests
:   [Source Code](https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-main:lint/libs/lint-tests/src/test/java/com/android/tools/lint/checks/SamDetectorTest.kt)

Kotlin's support for SAM (single abstract method) interfaces lets you
pass a lambda to the interface. This will create a new instance on the
fly even though there is no explicit constructor call. If you pass one
of these lambdas or method references into a method which (for example)
stores or compares the object identity, unexpected results may happen.

In particular, passing a lambda variable in as a listener, and then
later attempting to remove the listener will not work because a
different instance is passed in.

!!! Tip
   This lint check has an associated quickfix available in the IDE.

(##) Example

Here is an example of lint warnings produced by this check:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~text
src/test/pkg/test.kt:21:Warning: Implicit new MyInterface instance being
passed to method which ends up checking instance equality; this can lead
to subtle bugs [ImplicitSamInstance]
    handler.delete(lambda) // ERROR 1
                   ------
src/test/pkg/test.kt:22:Warning: Implicit new MyInterface instance being
passed to method which ends up checking instance equality; this can lead
to subtle bugs [ImplicitSamInstance]
    handler.compareIdentity1(lambda) // ERROR 2
                             ------
src/test/pkg/test.kt:23:Warning: Implicit new MyInterface instance being
passed to method which ends up checking instance equality; this can lead
to subtle bugs [ImplicitSamInstance]
    handler.compareIdentity2(lambda) // ERROR 3
                             ------
src/test/pkg/test.kt:31:Warning: Implicit new MyInterface instance being
passed to method which ends up checking instance equality; this can lead
to subtle bugs [ImplicitSamInstance]
    handler.delete(lambda2) // ERROR 4
                   -------
src/test/pkg/test.kt:35:Warning: Implicit new MyInterface instance being
passed to method which ends up checking instance equality; this can lead
to subtle bugs [ImplicitSamInstance]
    handler.delete(lambda3) // ERROR 5
                   -------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Here are the relevant source files:

`src/test/pkg/test.kt`:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~kotlin linenumbers
@file:Suppress("RedundantSamConstructor", "MoveLambdaOutsideParentheses")

package test.pkg

fun test(handler: MyHandler, list: List<MyInterface>) {
    handler.handle(MyInterface { println("hello") }) // OK
    handler.handle({ println("hello") }) // OK
    handler.stash(MyInterface { println("hello") }, list) // OK
    handler.stash({ println("hello") }, list) // OK
    handler.store({ println("hello") }) // OK
    handler.delete({ println("hello") }) // OK
    handler.delete(MyInterface { println("hello") }) // OK
    handler.compareIdentity1({ println("hello") }) // OK
    handler.compareIdentity2({ println("hello") }) // OK
    handler.compareEquals1({ println("hello") }) // OK
    handler.compareEquals2({ println("hello") }) // OK

    val lambda = { println("hello") }
    handler.stash(lambda, list) // OK
    handler.store(lambda) // OK
    handler.delete(lambda) // ERROR 1
    handler.compareIdentity1(lambda) // ERROR 2
    handler.compareIdentity2(lambda) // ERROR 3
    handler.compareEquals1(lambda) // OK
    handler.compareEquals2(lambda) // OK

    @Suppress("CanBeVal", "JoinDeclarationAndAssignment")
    var lambda2: () -> Unit
    lambda2 = { println("hello") }
    handler.stash(lambda2, list) // OK
    handler.delete(lambda2) // ERROR 4

    val lambda3: () -> Unit = { println("hello") }
    handler.stash(lambda3, list) // OK
    handler.delete(lambda3) // ERROR 5

    handler.act({ println("hello") }) // OK
    handler.act(::callback) // OK
}

fun callback() {}

fun viewpost(view: android.view.View) {
    view.postDelayed({ println ("Hello") }, 50)
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

`src/test/pkg/JavaTest.java`:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~java linenumbers
package test.pkg;

import java.util.List;

public class JavaTest {
    public void test(MyHandler handler, List<MyInterface> list) {
        handler.handle(() -> System.out.println("hello")); // OK
        handler.stash(() -> System.out.println("hello"), list); // OK
    }
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

`src/test/pkg/MyInterface.java`:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~java linenumbers
package test.pkg;

public interface MyInterface {
    void act();
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

`src/test/pkg/MyHandler.java`:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~java linenumbers
package test.pkg;

import java.util.List;

public class MyHandler {
    public void handle(MyInterface actor) {
        actor.act();
        System.out.println(actor);
        MyInterface copy = actor;
        System.out.println(copy);
    }

    public void stash(MyInterface actor, List<MyInterface> actors) {
        actors.add(actor);
    }

    public void store(MyInterface actor) {
        last = actor;
    }

    private MyInterface last;

    private void removeActor(MyInterface actor) {
    }

    public fun delete(MyInterface actor) {
        remove(actor);
    }

    public void compareIdentity1(MyInterface actor) {
        if (actor == last) {
            System.out.println("last");
        }
    }

    public void compareIdentity2(MyInterface actor) {
        if (actor != last) {
            System.out.println("not last");
        }
    }

    public void compareEquals1(MyInterface actor) {
        if (actor.equals(last)) {
            System.out.println("last");
        }
    }

    public void compareEquals2(MyInterface actor) {
        if (last.equals(actor)) {
            System.out.println("last");
        }
    }

    public void act(MyInterface actor) {
        if (actor != null) {
            actor.act();
        }
        //noinspection StatementWithEmptyBody
        if (actor == null) {
        } else {
            actor.act();
        }
    }
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You can also visit the
[source code](https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-main:lint/libs/lint-tests/src/test/java/com/android/tools/lint/checks/SamDetectorTest.kt)
for the unit tests for this check to see additional scenarios.

The above example was automatically extracted from the first unit test
found for this lint check, `SamDetector.testStashingImplicitInstances`.
To report a problem with this extracted sample, visit
https://issuetracker.google.com/issues/new?component=192708.

(##) Suppressing

You can suppress false positives using one of the following mechanisms:

* Using a suppression annotation like this on the enclosing
  element:

  ```kt
  // Kotlin
  @Suppress("ImplicitSamInstance")
  fun method() {
     problematicStatement()
  }
  ```

  or

  ```java
  // Java
  @SuppressWarnings("ImplicitSamInstance")
  void method() {
     problematicStatement();
  }
  ```

* Using a suppression comment like this on the line above:

  ```kt
  //noinspection ImplicitSamInstance
  problematicStatement()
  ```

* Using a special `lint.xml` file in the source tree which turns off
  the check in that folder and any sub folder. A simple file might look
  like this:
  ```xml
  &lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;lint&gt;
      &lt;issue id="ImplicitSamInstance" severity="ignore" /&gt;
  &lt;/lint&gt;
  ```
  Instead of `ignore` you can also change the severity here, for
  example from `error` to `warning`. You can find additional
  documentation on how to filter issues by path, regular expression and
  so on
  [here](https://googlesamples.github.io/android-custom-lint-rules/usage/lintxml.md.html).

* In Gradle projects, using the DSL syntax to configure lint. For
  example, you can use something like
  ```gradle
  lintOptions {
      disable 'ImplicitSamInstance'
  }
  ```
  In Android projects this should be nested inside an `android { }`
  block.

* For manual invocations of `lint`, using the `--ignore` flag:
  ```
  $ lint --ignore ImplicitSamInstance ...`
  ```

* Last, but not least, using baselines, as discussed
  [here](https://googlesamples.github.io/android-custom-lint-rules/usage/baselines.md.html).

<!-- Markdeep: --><style class="fallback">body{visibility:hidden;white-space:pre;font-family:monospace}</style><script src="markdeep.min.js" charset="utf-8"></script><script src="https://morgan3d.github.io/markdeep/latest/markdeep.min.js" charset="utf-8"></script><script>window.alreadyProcessedMarkdeep||(document.body.style.visibility="visible")</script>